import React from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, notification, Modal, Upload, Tooltip } from 'antd';
import { addKeyWords, } from '@/services/resource';
import { baseUrl } from '@/utils/config.js'
import { checkBeforeFileUpload } from '@/utils/utils'

const FormItem = Form.Item;

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
    },
};


class Edit extends React.Component {
    constructor(argus) {
        super(argus);

        this.state = {
            fileList: [], // 上传文件成员
            loading: false,
        };
    }

    infoToParent(key) {
        this.props.callBack(key);
    }

    // 提交修改的内容
    handleUserSubmit = e => {
        e.preventDefault();
        const _this = this;
        const { fileList, } = this.state;
        const { form, labelId } = this.props;
        form.validateFields((err) => {
            if (!err) {
                const formData = new FormData();
                if (fileList.length == 0) {
                    _this.props.form.setFields({
                        files: {
                            errors: [new Error('请上传文件!')],
                        },
                    });
                    return;
                }
                fileList.forEach(file => {
                    formData.append('file', file);
                });
                formData.append('dictionary_label_id', labelId - 0);
                _this.setState({ loading: true, })
                addKeyWords(formData).then(res => {
                    if (res.retCode == '0') {
                        notification['success']({
                            message: '操作成功',
                            key: '上传',
                            description: '上传成功',
                        });
                        _this.props.callBack(false);
                    } else { _this.setState({ loading: false, }) }
                })
            }
        });
    };

    render() {
        const { getFieldDecorator } = this.props.form;
        const { loading, fileList, } = this.state;
        const { isShowAddKeyWordByFileModel, } = this.props;
        const props = {
            multiple: true,
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: (file, fileLists) => {
                let find = fileList.find(item => item.name === file.name);
                let isAcceptFileType = checkBeforeFileUpload(file, ['txt']);
                if (!isAcceptFileType.tip) {
                    notification['warning']({
                        message: '警告',
                        key: isAcceptFileType.msg,
                        description: isAcceptFileType.msg
                    });
                    return true;
                }
                if (find) {
                    notification['warning']({
                        message: '警告',
                        key: '存在同名文件',
                        description: '存在同名文件'
                    });
                    return true;
                } else {
                    if (fileLists.length > 5 - this.state.fileList.length) {
                        notification['warning']({
                            message: '警告',
                            key: '每次上传文件个数不超过5个',
                            description: '每次上传文件个数不超过5个'
                        });
                        return true;
                    } else {
                        this.setState(state => ({
                            fileList: [...state.fileList, file],
                        }));
                        return false;
                    }
                }
            },
            fileList,
        };

        return (
            <span>

                <Modal
                    title={`上传`}
                    maskClosable={false}
                    visible={isShowAddKeyWordByFileModel}
                    width={600}
                    onCancel={this.infoToParent.bind(this, false)}
                    footer={[
                        <Button key="cancel" onClick={this.infoToParent.bind(this, false)}>取消</Button>,
                        <Button key="primary" type='primary' loading={loading} onClick={this.handleUserSubmit}>确定</Button>
                    ]}
                >
                    <Form>
                        <Form.Item label='上传文件' style={{ marginBottom: 0 }} {...formItemLayout}>
                            <div className="dropbox">
                                {getFieldDecorator('files', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请上传文件!',
                                        },
                                    ],
                                })(
                                    <span>
                                        <Upload {...props} accept=".txt">
                                            <Button size='small'>
                                                <UploadOutlined /> 点击上传
                                            </Button>
                                        </Upload>
                                        <span style={{ padding: '6px 4px', backgroundColor: 'rgba(240, 242, 245, 1)' }}>支持扩展名：.txt <a target='_blank' download={'模板'} className="ant-dropdown-link" type='link' href={baseUrl + '/templates/keywords'}>下载示例模板</a></span>
                                    </span>
                                )}
                            </div>
                        </Form.Item>
                    </Form>
                </Modal>
            </span>
        );
    }
}

const AddKeyWords = Form.create()(Edit);

export default AddKeyWords;